const useModel = require('../model/useModel');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');
class UserController{
	//加密密码
	hashpwd(pwd){
		return new Promise((resolve,reject)=>{
			    bcrypt.hash(pwd, 10, function(err, hash) {
					if(!err){
						resolve(hash);
					}
			    });
		})
	}
	//解译密码
	comparepwd(pwd,hashpwd){
		return new Promise((resolve,reject)=>{
			bcrypt.compare(pwd, hashpwd, function(err, res) {
				if(!err){
					resolve(res);
				}
			});
		})
	}
	//创建token
	_createToken(username) {
	    // return jwt.sign(username, 'lagou');
	    let privateKey = fs.readFileSync(path.resolve(__dirname, '../key/rsa_private_key.pem'));
	    var token = jwt.sign(username, privateKey, { algorithm: 'RS256' });
	    return token;
	 }
	
	
	async signin(req,res,next){
		let { username,password } = req.body;
		let findResult = await useModel.find({username});
		if(findResult.length&&findResult[0].username){
			res.send({code:0,msg:"用户名重复"});
			return;
		}
		// let hashpwd = await userController.hashpwd(password);
		let signinResult = await useModel.save({username,password});
		if(signinResult){
			res.send({code:1,msg:"用户注册成功"});
		}else{
			res.send({code:0,msg:"用户注册失败"})
		}
		
	}
	async login(req,res,next){
		let { username,password } = req.body;
		let findresult = await useModel.find({username,password});
		if(findresult.length){
			res.set('X-ACCESS-TOKEN', userController._createToken(findresult[0].username))
			req.session.username = req.body.username;
			res.send({code:1,msg:"用户名已找到",username:req.body.username})
		}else{
			res.send({code:0,msg:"用户名未找到"})
		}
	}
	//根据req.session来判断当前页面是否为登录状态
	islogin(req,res){
		if(req.session.username){
			res.send({code:1,msg:"当前为登录状态",username:req.session.username});
		}else{
			res.send({code:0,msg:"当前为未登录状态"})
		}
	}
	//退出当前登录状态
	layout(req,res){
		req.session.username = null;
		res.send({code:1,msg:"退出登录成功!"})
	}
}
const userController = new UserController();
module.exports = userController;
